package com.xplay.xpocker.observer;

import com.xplay.xpocker.meta.MessageContent;
import com.xplay.xpocker.meta.user.MetaUserChannel;
import com.xplay.xpocker.socket.UserChannelMate;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * @author wanjie
 * @date 2021/3/22 17:10
 */
@Data
public class SubscriptionSubject implements Subject, UserChannelMate {

    private static Logger log = LoggerFactory.getLogger(SubscriptionSubject.class);
    // 存储桌面上的所有玩家
    private LinkedList<MetaUserChannel> subjectUsers = new LinkedList<>();

    @Override
    public void attach(MetaUserChannel observer) {
        boolean tag = false;
        for (MetaUserChannel ob : subjectUsers) {
            if (ob.getUserId().equals(observer.getUserId())) {
                tag = true;
                if (ob.getUserCtx().channel().isOpen()) {
                    ob.getUserCtx().channel().close();
                }
                ob.setChannel(observer.getUserCtx());
            }
        }
        if (!tag) {
            subjectUsers.add(observer);
        }
    }


    @Override
    public void detach(MetaUserChannel observer) {
        Iterator<MetaUserChannel> iterator = subjectUsers.iterator();
        if (iterator.hasNext()) {
            if (iterator.next().getUserId().equals(observer.getUserId())) {
                iterator.remove();
            }
        }
    }

    @Override
    public void notifyMessage(MessageContent message, String userId) {
        log.info("------用户总数-----------" + subjectUsers.size());
        for (MetaUserChannel ob : subjectUsers) {
            try {
                if (userId == null) {
                    senMessage(ob.getUserCtx(), message);
                } else if (!ob.getUserId().equals(userId)) {
                    senMessage(ob.getUserCtx(), message);
                }
            } catch (Exception e) {
                log.info(String.format("当前消息未发送成功=====%s", message.toString()));
            }
        }
    }


    @Override
    public ChannelHandlerContext getUserChannelByUserId(String userId) {
        for (MetaUserChannel ob : subjectUsers) {
            if (ob.getUserId().equals(userId)) {
                return ob.getUserCtx();
            }
        }
        return null;
    }

    @Override
    public ChannelHandlerContext getUserChannelBySeq(Integer seq) {
        for (MetaUserChannel ob : subjectUsers) {
            if (ob.getSeq() == seq) {
                return ob.getUserCtx();
            }
        }
        return null;
    }
}
